package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.*;

import com.weilai.service.*;
import com.weilai.service.serviceImpl.CategoriesServiceImpl;

import com.weilai.service.serviceImpl.DraftsServiceImpl;
import com.weilai.service.serviceImpl.ReportInfoServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Api(tags = "用户相关操作", description = "用来提供 用户相关方法的接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PostsService postsService;
    @Autowired
    private CategoriesServiceImpl categoriesService;
    @Autowired
    private DraftsServiceImpl draftsService;
    @Autowired
    private ReportInfoService reportInfoService;
    @Autowired
    private LikesService likesService;
    @Autowired
    private ThoughtService thoughtService;
    @Autowired
    private VideosService videosService;
    @Autowired
    private FollowersService followersService;
    @Autowired
    private BackgroundService backgroundService;
    @Autowired
    private CommentsService commentsService;

    //退出登录
    @PostMapping("/exit")
    public ModelAndView exit(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);

            if (session == null) {
                // 如果会话不存在，说明用户已经退出或会话已过期
                throw new BusinessException(Code.SYSTEM_TIMEOUT_ERROR, "当前没有活跃的会话");
            }

            // 使会话失效
            session.invalidate();

            // 重定向到登录页
            return new ModelAndView("redirect:/login");

        } catch (IllegalStateException e) {
            // 会话已经失效的情况下调用invalidate()会抛出此异常
            throw new BusinessException(
                    Code.SYSTEM_TIMEOUT_ERROR,
                    "会话已失效：" + e.getMessage()
            );
        } catch (Exception e) {
            // 其他未预料到的异常
            throw new SystemException(
                    Code.SYSTEM_UNKNOWN_ERROR,
                    "退出登录时发生系统错误",
                    e
            );
        }
    }

    //账号注销
    @PostMapping("/writeOff")
    @ResponseBody // 添加该注解表示返回JSON数据
    public Map<String, Object> logout(@RequestParam int userId, HttpServletRequest request) {

        System.out.println("logout方法....");
        Map<String, Object> response = new HashMap<>();
        HttpSession session = request.getSession();

        try{
            // 获取当前会话
            if (session == null || session.getAttribute("userId") == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "未登录");
            }

            // 验证请求的userId与会话中的userId是否一致
            int sessionUserId = (int) session.getAttribute("userId");
            if (userId != sessionUserId) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "权限不足");
            }

            // 删除用户基本信息
            if (!userService.deleteUserById(userId)) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
            }

            // 删除用户关联数据（这些操作即使部分失败也应继续执行）
            postsService.deleteByUserId(userId);
            likesService.deleteUserById(userId);
            thoughtService.deleteUserById(userId);
            videosService.deleteUserById(userId);
            followersService.deleteUserById(userId);
            draftsService.deleteUserById(userId);
            commentsService.deleteCommentByUserId(userId);

            // 清除会话
            session.invalidate();

            // 构建成功响应
            response.put("success", true);
            response.put("message", "账号注销成功");
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "账号注销失败", e);
        }

        return response;
    }

    //2.14用户在创作者中心管理自己发布的帖子，草稿箱等内容
    //查询用户所有的帖子
    @ApiOperation(value = "跳转创作者中心的内容管理")
    @ApiResponses({
            @ApiResponse(code = 200, message = "跳转成功")
    })
    //跳转内容管理
    @GetMapping("/creatorCenterContent")
    public ModelAndView creatorCenterContent(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();

        try {
            // 检查用户是否登录
            int id = (int)session.getAttribute("userId");
            User user = (User)session.getAttribute("user");
            if (user == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "请先登录");
            }
            mav.addObject("user", user);
            mav.addObject("backgroundUrl",backgroundService.getByUserId(id).getUrl());

            // 获取文章
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("posts", posts);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("creatorCenterContent");
            return mav;

        } catch (BusinessException e) {
            // 业务异常直接抛出，由全局异常处理器处理
            throw e;
        } catch (Exception e) {
            // 未知系统异常转换为SystemException
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "加载个人主页失败", e);
        }
    }

    @ApiOperation(value = "获取视频", notes = "")
    //获取视频
    @GetMapping("/creatCenterVideo")
    public ModelAndView videos(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取视频
        List<Videos> videos;
        try {
            videos = videosService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("videos", videos);
            mav.addObject("videosNum", videos.size());
            mav.setViewName("creatCenterVideo");

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取视频数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取想法", notes = "")
    //获取想法
    @GetMapping("/views")
    public ModelAndView views(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取想法
        List<Thought> Thoughts;
        try {
            Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("Thoughts", Thoughts);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("creatCenterIdea");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取想法数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取点赞的帖子的方法", notes = "快捷访问点赞的帖子，会传递帖子集合、点赞帖子数量")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功")
    })
    //获取点赞的帖子...
    @GetMapping("/creatCenterLike")
    public ModelAndView likes(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        try {
            // 获取点赞的帖子
            List<Likes> likes = likesService.getLikesByUserId(id);
            List<Posts> likePosts = new ArrayList<>();
            for (Likes like : likes) {
                try {
                    Posts post = postsService.selectById(like.getPostId());
                    if (post != null) {
                        likePosts.add(post);
                    }
                } catch (Exception e) {
                    throw new SystemException(Code.SYSTEM_DB_ERROR, "获取点赞数据失败", e);
                }
            }
            List<User> likesUsers = new ArrayList<>();
            for (Posts likePost : likePosts) {
                User u=userService.getUserById(likePost.getUserId());
                u.setPassword("****");
                likesUsers.add(u);
            }
            mav.addObject("user", user);
            mav.addObject("likesUsers", likesUsers);
            mav.addObject("likePosts", likePosts);
            mav.addObject("likesNum", likePosts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("creatCenterLike");
        } catch (Exception e) {
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "获取点赞帖子失败",
                    e
            );
        }
        return mav;
    }

    @ApiOperation(value = "获取关注者的方法", notes = "快捷访问关注者")
    //关注
    @GetMapping("/creatCenterFollower")
    public ModelAndView follower(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取关注
        try {
            List<User> follower = followersService.selectFollowingsById(id);
            for (User u : follower) {
                u.setPassword("****");
            }
            mav.addObject("user", user);
            mav.addObject("follower", follower);
            mav.addObject("followersNum", follower.size());
            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            mav.setViewName("creatCeaterFollower");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }
    @ApiOperation(value = "获取粉丝的方法", notes = "快捷访问粉丝")
    //粉丝
    @GetMapping("/creatCenterFan")
    public ModelAndView fans(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取粉丝
        try {
            List<User> fans = followersService.selectFansById(id);
            int[] followEachOther = new int[fans.size()];
            int i=0;
            for (User u : fans) {
                u.setPassword("****");
                if(followersService.isFollowing(id, u.getId())){
                    followEachOther[i]=1;
                }
                else{
                    followEachOther[i]=0;
                }
                i++;
            }
            mav.addObject("user", user);
            mav.addObject("fans", fans);
            mav.addObject("fansNum", fans.size());
            mav.addObject("followEachOther",followEachOther);

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("creatCenterFan");

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }



    //修改单独某个帖子,前端把帖子id传过来
    //用于回显数据
    @ApiOperation(value = "用户单独修改某个帖子时，该方法用于回显数据")
    @GetMapping("/echoMyPost")
    public ModelAndView echoMyPost(@RequestParam("id") int id) {
        Posts post = postsService.selectById(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("echoPost", post);
        mav.setViewName("updataMyPost");
        return mav;
    }

    //再修改数据
    @ApiOperation(value = "该方法用于保存用户修改的数据")
    @PostMapping("/manageMyPost")
    public ModelAndView ManageMyPost(@RequestParam("id") int postId,
                                     @RequestParam("title") String title,
                                     @RequestParam("content") String content,
                                     @RequestParam("type") String type,
                                     @RequestParam("categoryName") String name,
                                     @RequestParam("imageUrl") String imageUrl) {
        ModelAndView mav = new ModelAndView();
        Categories categories = categoriesService.selectByName(name);
        if (categories == null) {
            //不存在该分类
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "分类不存在");
        } else {
            Posts newPost = new Posts();
            newPost.setId(postId);
            newPost.setTitle(title);
            newPost.setContent(content);
            newPost.setType(type);
            newPost.setImageUrl(imageUrl);
            newPost.setCategoryName(name);
            postsService.update(newPost);
            mav.addObject("info", "修改成功");
        }

        mav.setViewName("toManageMyPosts");

        return mav;
    }

    //查看草稿箱
    @ApiOperation(value = "该方法用于查询所有的草稿")
    @GetMapping("/toSelectDrafts")
    public ModelAndView selectDrafts(HttpServletRequest request){

        User user =(User) request.getSession().getAttribute("user");
        List<Drafts> drafts = draftsService.selectByUserId(user.getId());
        ModelAndView mav=new ModelAndView();
        mav.addObject("draftList",drafts);
        mav.setViewName("/selectDrafts");
        return mav;
    }
    //存草稿功能
    @ApiOperation(value = "该方法用于保存草稿内容")
    @PostMapping("/saveDraft")
    public ModelAndView saveDraft(@RequestParam("id")int postId,
                                  @RequestParam("title") String title,
                                  @RequestParam("content") String content,
                                  @RequestParam("type") String type,
                                  @RequestParam("categoryName") String categoryName,
                                  @RequestParam("imageUrl")String imageUrl,
                                  HttpServletRequest request
    ) {
        User user =(User) request.getSession().getAttribute("user");
        ModelAndView mav = new ModelAndView();
        Drafts drafts = draftsService.selectByPostId(postId);
        Drafts newDrafts=new Drafts();
        newDrafts.setPostId(postId);
        newDrafts.setTitle(title);
        newDrafts.setContent(content);
        newDrafts.setCategoryName(categoryName);
        newDrafts.setUserId(user.getId());
        newDrafts.setImageUrl(imageUrl);
        if(drafts==null){
            // 该帖子无草稿-->insert
            draftsService.addDrafts(newDrafts);
        }else{
            // 该帖子有草稿-->update
            draftsService.updateDrafts(newDrafts);
        }

        mav.addObject("info", "草稿保存成功");
        mav.setViewName("toManageMyPosts");
        return mav;
    }

    //举报他人
    @ApiOperation(value = "举报他人，跳转到填写举报信息的页面的同时，获取被举报帖子id")
    @GetMapping("/toReportOthers")
    public ModelAndView toReportOthers(@RequestParam("postId")int postId){
        ModelAndView mav=new ModelAndView();
        mav.addObject("postId",postId);
        mav.setViewName("report");
        return mav;
    }

    //举报
    @ApiOperation(value = "举报他人，填写举报信息")
    @PostMapping("/reportOthers")
    public ModelAndView ReportOthers(@RequestParam("postId")int postId,
                                     HttpServletRequest request,
                                     @RequestParam("reportType")String reportType,
                                     @RequestParam("reportReason")String reportReason
                                     ){
        ReportInfo reportInfo=new ReportInfo();
        reportInfo.setPostId(postId);
        User user = (User)request.getSession().getAttribute("user");
        int userId=user.getId();
        reportInfo.setReporterId(userId);
        reportInfo.setReportType(reportType);
        reportInfo.setReportReason(reportReason);
        reportInfoService.reportOthers(reportInfo);
        ModelAndView mav=new ModelAndView();
        mav.addObject("info","举报成功");
        mav.setViewName("redirect:/mainPageRecommend");

        return mav;
    }


}
